package com.wuzhun.wxmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuzhun.wxmp.common.ResultCode;
import com.wuzhun.wxmp.common.ServiceException;
import com.wuzhun.wxmp.mapper.TokenMapper;
import com.wuzhun.wxmp.model.dto.TokenDTO;
import com.wuzhun.wxmp.model.entity.Token;
import com.wuzhun.wxmp.service.ITokenService;
import com.wuzhun.wxmp.util.DateTimeUtil;
import com.wuzhun.wxmp.util.StringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 用户登录Token表 服务实现类
 * </p>
 *
 * @author renbaolin
 * @since 2022-12-05
 */
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements ITokenService {

    @Resource
    private TokenMapper tokenMapper;

    @Override
    public TokenDTO queryTokenByUid(Integer uid) {
        Token token = tokenMapper.selectOne(new QueryWrapper<Token>().eq("uid", uid).last("limit 1").orderByDesc("id"));
        return covertToken(token);
    }

    @Override
    public TokenDTO generateAndInsert(Integer uid, String ip) {
        Token token = new Token();
        token.setUid(uid);
        int tokenExpireDay = 30;
        token.setExpireTime(DateTimeUtil.getDateByIncreaseDay(tokenExpireDay));
        token.setIp(ip);
        token.setToken(StringUtil.generateToken(uid));
        tokenMapper.insert(token);
        return covertToken(token);
    }

    @Override
    public boolean verifyToken(String token) {
        return verifyToken(queryToken(token));
    }

    @Override
    public Integer queryUidByToken(String token) {
        Token dbToken = queryToken(token);
        if (!verifyToken(dbToken)) {
            throw new ServiceException(ResultCode.INVALID_TOKEN);
        }
        return dbToken.getUid();
    }

    /**
     * 模型转换
     *
     * @param token
     * @return
     */
    private TokenDTO covertToken(Token token) {
        if (token == null) {
            return null;
        }
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token.getToken());
        tokenDTO.setUid(token.getUid());
        tokenDTO.setExpireTime(token.getExpireTime());
        tokenDTO.setIp(token.getIp());
        return tokenDTO;
    }

    /**
     * 查询token
     *
     * @param token
     * @return
     */
    private Token queryToken(String token) {
        return tokenMapper.selectOne(new QueryWrapper<Token>().eq("token", token).orderByDesc("id"));
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    private boolean verifyToken(Token token) {
        return token != null && token.getExpireTime().getTime() > System.currentTimeMillis();
    }
}
